var $dataInfo = $('#opportunityInfo');

//防止表头与表格不对齐
$(window).resize(function () {
    $dataInfo.bootstrapTable('resetView');
});


$(function () {
    /*//预计签单时间
    $('#estimatedSigningTime').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //预计签单时间
    $('#estimatedSigningTimeAdd').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //最后跟进时间
    $('#lastFollowUpTime').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //下次跟进时间
    $('#nextFollowUpTime').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //商机获取日期
    $('#opportunityAcquisitionTime').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });*/

    dataInfoInit();
});

/**
 * 商机管理
 */
function dataInfoInit() {
    //先销毁表格
    $dataInfo.bootstrapTable('destroy');
    $dataInfo.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/opportunity/selectOpportunityVoList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        // fixedRightNumber: 1,    // 右侧固定列

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'opportunityId', visible: false},
            {title: '客户id', field: 'customerId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '商机标题', field: 'opportunityTitle', align: 'left', valign: 'middle',formatter: opportunityTitleFormat},
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle',formatter: customerNameFormat},
            {title: '客户联系人', field: 'contactName', align: 'left', valign: 'middle',formatter: contactNameFormat},
            {title: '商机状态', field: 'opportunityStatus', align: 'left', valign: 'middle',formatter: opportunityStatusFormat},
            {title: '商机类型', field: 'opportunityTp', align: 'left', valign: 'middle',formatter: opportunityTpFormat},
            //{title: '输单友商', field: 'lostOrderFriend', align: 'left', valign: 'middle'},
            {title: '所有人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle',formatter:dateFormat},
            //{title: '预计签单时间', field: 'estimatedSigningTime', align: 'left', valign: 'middle',formatter:dateFormat},
            {title: '最后跟进时间', field: 'lastFollowUpTime', align: 'left', valign: 'middle',formatter:dateFormat},
            //{title: '所有人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'left',events: operateEvents, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}


/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    return [
        '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="查看" data-toggle="tooltip"><i class="mdi mdi-eye"></i>查看</a>'
    ].join('');
}

window.operateEvents = {
    //查看点击事件
    'click #detail': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '商机详情',
            url : "/front/opportunityManager/opportunityDetail?opportunityId=" + row.opportunityId
        }, true);
    }
};

/**
 * 点击商机标题跳转商机详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function opportunityTitleFormat(value, row, index) {
    //return '<a style="color:blue;cursor:pointer;text-decoration:underline;" target="_blank"  onclick=\'opportunityDetail(\"'+row.opportunityId+'")\'>'+value+'</a>';
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else{
        return '<a href="JavaScript:void(0);" onclick=\'opportunityDetail(\"'+row.opportunityId+'")\'>'+value+'</a>';
    }
}

function  opportunityDetail(opportunityId) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '商机详情',
        url : "/front/opportunityManager/opportunityDetail?type=admin&opportunityId=" + opportunityId
    }, true);
}

/**
 * 点击客户姓名跳转客户详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerNameFormat(value, row, index) {
    //return '<a href="JavaScript:void(0);"  onclick=\'customerDetail(\"'+row.customerId+'")\'>'+value+'</a>';
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else{
        return '<a href="JavaScript:void(0);" onclick=\'customerDetail(\"'+row.customerId+'")\'>'+value+'</a>';
    }
}

function  customerDetail(customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '客户详情',
        url: "/front/customerManager/customerDetail?customerId=" + customerId
    },true);
}

/**
 * 点击联系人姓名跳转联系人详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactNameFormat(value, row, index) {
    //return '<a style="color:blue;cursor:pointer;text-decoration:underline;" target="_blank"  onclick=\'contactDetail(\"'+row.contactId+'")\'>'+value+'</a>';
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else{
        return value;
        // return '<a href="JavaScript:void(0);" onclick=\'contactDetail(\"'+row.contactId+'")\'>'+value+'</a>';
    }
}

function  contactDetail(contactId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '联系人详情',
        url: "/front/contactManager/contactDetail?contactId=" + contactId
    },true);
}


/**
 * 拼接客户表格查询条件参数
 */
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //普通搜索条件
    params.dateType = $("#dateType").val();  //全部 本月 本周
    params.customerName = $.trim($('#customerName').val());  //客户名称
    //params.estimatedSigningTime = $("#estimatedSigningTime").val();  //预计签约时间
    params.opportunityTp = $("#opportunityTp").val();  //商机类型
    params.opportunityStatus = $('#opportunityStatus').val();  //商机状态
    params.bs = '0';  //0管理端 1用户端
    return params;
}

function queryParamsMin(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //普通搜索条件
    params.dateType = $("#dateType").val();  //全部 本月 本周
    params.customerName = $.trim($('#customerNameMin').val());  //客户名称
    params.bs = '0';  //0管理端 1用户端
    return params;
}


/**
 * 商机状态
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function opportunityStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>初步洽谈</span>";
    } else if (2 == value) {
        return "<span class='label label-yellow-light'>需求确定</span>";
    } else if (3 == value) {
        return "<span class='label label-info-light'>方案报价</span>";
    } else if (4 == value){
        return "<span class='label label-purple-light'>谈判</span>";
    }else if (5 == value){
        return "<span class='label label-purple-light'>洽谈合同</span>";
    }else if (6 == value){
        return "<span class='label label-purple-light'>赢单</span>";
    }else if (7 == value){
        return "<span class='label label-purple-light'>输单</span>";
    }
}

/**
 * 商机类型 1:续费 2:新会员 3:单词 4:证书 5:线上单品 6:高端班 7:内训 8:咨询 9:其他
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function opportunityTpFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>续费</span>";
    } else if (2 == value) {
        return "<span class='label label-yellow-light'>新会员</span>";
    } else if (3 == value) {
        return "<span class='label label-info-light'>单次</span>";
    } else if (4 == value){
        return "<span class='label label-purple-light'>证书</span>";
    }else if (5 == value){
        return "<span class='label label-purple-light'>线上单品</span>";
    }else if (6 == value){
        return "<span class='label label-purple-light'>高端班</span>";
    }else if (7 == value){
        return "<span class='label label-purple-light'>内训</span>";
    }else if (8 == value){
        return "<span class='label label-purple-light'>咨询</span>";
    }else if (9 == value){
        return "<span class='label label-purple-light'>组合</span>";
    }else if (10 == value){
        return "<span class='label label-purple-light'>行业会</span>";
    }else if (11 == value){
        return "<span class='label label-purple-light'>其他</span>";
    }
}

/**
 * 时间转换
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function dateFormat(value, row, index) {
    if (value != null) {
        var date = new Date(value);
        var month = date.getMonth()+1;
        var tian = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (tian >= 1 && tian <= 9) {
            tian = "0" + tian;
        }

        return date.getFullYear() + '-' + month + '-' + tian;
    }
}

function searchMyCustomerPool(type){
    $('.all').addClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $("#dateType").val("all");
    if (type == 1) {
        $dataInfo.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParamsMin});
    } else {
        $dataInfo.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }

}

/**
 * 全部/周/月切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    $('#createTm').val('');//清空创建时间搜索条件
    $dataInfo.bootstrapTable('refreshOptions', {pageNumber: 1});
}

//切换tab页的时候清空所有数据
function clearAllData() {
    //全部 本年 本月 本周
    $('.all').addClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $("#dateType").val("all");
    //客户名称
    $('#customerName').val('');

    //预计签单时间
    //$('#estimatedSigningTime').val('');

    //商机类型
    $('#opportunityTp').val('');

    //商机状态
    $('#opportunityStatus').val('');
}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

function resetSearch(_this){
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    } else {
        searchForm = $(_this).parents('#filterContent');
    }
    searchForm.find('input[type="text"]').val('');
    searchForm.find('select').find('option:first').prop('selected', 'selected');
    searchForm.find('select').selectpicker('refresh');
    if($(_this).parents('#filterContent').context !== document) {
        dataInfoInit();
    }
}

